/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import model.Attempt;
import model.PublicUser;
import util.gv.GVServerPath;

public class Email {

    String emailServerName = "smtp.gmail.com";
    String emailFromAddress = "iepm.ncode@gmail.com";
    String emailFromPassword = "12345678#";
    String toEmailAddress;
    String mailer = "JavaMailer";
    String directory = GVServerPath.ServerPath;
    
    String resetPasswordEmailTemplate = directory + "resetPasswordEmailTemplate.txt";
    String newSystemUserEmailTemplate = directory + "newSystemUserEmailTemplate.txt";
    String retrieveReportEmailTemplate = directory + "retrieveReportEmailTemplate.txt";
    String newReportEmailTemplate = directory + "newReportEmailTemplate.txt";

    public Email() {
    }

    public boolean emailUserNewPassword(String toEmail, String password, String username) throws Exception {
        toEmailAddress = toEmail;

        ReadFile rf = new ReadFile();
        String[] emailInfo = rf.readTextFile(resetPasswordEmailTemplate);

        if (emailInfo[2].isEmpty()) {
            String subject = emailInfo[0];
            String contents = emailInfo[1];

            contents = contents.replace("{{name}}", username);
            contents = contents.replace("{{username}}", toEmail);
            contents = contents.replace("{{password}}", password);

            Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator(emailFromAddress, emailFromPassword);
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject(subject);
                String messageText = contents;
                msg.setContent(messageText, "text/html");
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }

            return true;
        } else {
            return false;
        }
    }

    public boolean emailUserPassword(String toEmail, String password, String username) throws Exception {
        toEmailAddress = toEmail;

        ReadFile rf = new ReadFile();
        String[] emailInfo = rf.readTextFile(newSystemUserEmailTemplate);

        if (emailInfo[2].isEmpty()) {
            String subject = emailInfo[0];
            String contents = emailInfo[1];

            contents = contents.replace("{{name}}", username);
            contents = contents.replace("{{username}}", toEmail);
            contents = contents.replace("{{password}}", password);

            Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator(emailFromAddress, emailFromPassword);
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject(subject);
                String messageText = contents;
                msg.setContent(messageText, "text/html");
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return true;
        } else {
            return false;

        }
    }

    public boolean emailReportLinks(String toEmail, PublicUser pu, String pathLink) throws Exception {
        toEmailAddress = toEmail;

        ReadFile rf = new ReadFile();
        String[] emailInfo = rf.readTextFile(retrieveReportEmailTemplate);

        if (emailInfo[2].isEmpty()) {
            String subject = emailInfo[0];
            String contents = emailInfo[1];
            contents = contents.replace("{{name}}", pu.getName());

            String loopContents = contents.substring(contents.indexOf("[{Start of Loop}]") + 16 + 1, contents.indexOf("[{End of Loop}]"));
            String filledLoopContents = "";
            ArrayList<Attempt> attempts = new ArrayList(pu.getAttempt());

            Collections.reverse(attempts);

            for (Attempt a : attempts) {
                if (a.getStatus().equals(Attempt.SurveyStatus.Acceptable) || a.getStatus().equals(Attempt.SurveyStatus.Completed)) {
                    String eachLoopContents = loopContents + "<br/>";
                    String link = "http://" + pathLink + "?action=getReport&getPDF=" + a.getLink();
                    eachLoopContents = eachLoopContents.replace("{{link}}", link);

                    String reportID = a.getAttempt_id() + "";
                    eachLoopContents = eachLoopContents.replace("{{report id}}", reportID);

                    String timeStamp = a.getTimestamps().toString();
                    eachLoopContents = eachLoopContents.replace("{{date completed}}", timeStamp);

                    filledLoopContents = filledLoopContents + eachLoopContents + " ";
                }
            }

            String filledContents = contents.substring(0, contents.indexOf("[{Start of Loop}]"))
                    + filledLoopContents
                    + contents.substring(contents.indexOf("[{End of Loop}]") + 15)
                    + "";

            contents = filledContents;

            Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");



            javax.mail.Authenticator auth = new SMTPAuthenticator(emailFromAddress, emailFromPassword);
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject(subject);
                String messageText = contents;
                msg.setContent(messageText, "text/html");
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return true;
        } else {
            return false;

        }
    }

    public boolean emailNewReportLink(String toEmail, PublicUser pu, String pathLink, Attempt attempt) throws Exception {
        toEmailAddress = toEmail;

        ReadFile rf = new ReadFile();
        String[] emailInfo = rf.readTextFile(newReportEmailTemplate);

        if (emailInfo[2].isEmpty()) {
            String subject = emailInfo[0];
            String contents = emailInfo[1];
            contents = contents.replace("{{name}}", pu.getName());

            String newReportlink = "http://" + pathLink + "?action=getReport&getPDF=" + attempt.getLink();
            contents = contents.replace("{{new report link}}", newReportlink);

            contents = contents.replace("{{new report id}}", attempt.getAttempt_id() + "");
            contents = contents.replace("{{new date completed}}", attempt.getTimestamps().toString());

            String filledContents = contents;

            if (contents.contains("[{Start of Loop}]") && contents.contains("[{End of Loop}]")) {
                String loopContents = contents.substring(contents.indexOf("[{Start of Loop}]") + 16 + 1, contents.indexOf("[{End of Loop}]"));
                String filledLoopContents = "";
                ArrayList<Attempt> attempts = new ArrayList(pu.getAttempt());

                Collections.reverse(attempts);

                for (Attempt a : attempts) {
                    if (a.getStatus().equals(Attempt.SurveyStatus.Acceptable) || a.getStatus().equals(Attempt.SurveyStatus.Completed)) {

                        if (a.getAttempt_id() != attempt.getAttempt_id()) {
                            String eachLoopContents = loopContents + "<br/>";
                            String link = "http://" + pathLink + "?action=getReport&getPDF=" + a.getLink();
                           
                            eachLoopContents = eachLoopContents.replace("{{past report link}}", link);

                            String reportID = a.getAttempt_id() + "";
                            eachLoopContents = eachLoopContents.replace("{{past report id}}", reportID);

                            String timeStamp = a.getTimestamps().toString();
                            eachLoopContents = eachLoopContents.replace("{{past date completed}}", timeStamp);

                            filledLoopContents = filledLoopContents + eachLoopContents + " ";
                        }
                    }

                }

                filledContents = contents.substring(0, contents.indexOf("[{Start of Loop}]"))
                        + filledLoopContents
                        + contents.substring(contents.indexOf("[{End of Loop}]") + 15)
                        + "";

            }


            contents = filledContents;

            Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");



            javax.mail.Authenticator auth = new SMTPAuthenticator(emailFromAddress, emailFromPassword);
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject(subject);
                String messageText = contents;
                msg.setContent(messageText, "text/html");
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return true;
        } else {
            return false;

        }
    }
}
